/**
 */
package com.dingpeikeji.quickdeer.core.modules.gov.web;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alipay.api.RefundFastpayByPlatformNopwdApi;
import com.alipay.model.RefundFastpayByPlatformNopwdReq;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrdersOut;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersOutService;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.payinfo.entity.TPayinfo;
import com.dingpeikeji.quickdeer.core.modules.realsche.entity.TRealsche;
import com.dingpeikeji.quickdeer.core.modules.realsche.service.TRealscheService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.SysAds;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.mobile.entity.CitySceneryInfo;
import com.dingpeikeji.quickdeer.mobile.entity.DestinationInfo;
import com.dingpeikeji.quickdeer.mobile.entity.TripCounselorInfo;
import com.dingpeikeji.quickdeer.mobile.service.OrderService;
import com.dingpeikeji.quickdeer.mobile.web.MobileJsonController;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.interceptor.FrontBaseInterceptor;
import com.dingpeikeji.quickdeer.modules.rcpt.entity.TRcpt;
import com.dingpeikeji.quickdeer.modules.rcpt.entity.TUsersRcpt;
import com.dingpeikeji.quickdeer.modules.rcpt.service.TRcptService;
import com.dingpeikeji.quickdeer.modules.rcpt.service.TUsersRcptService;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.DemandsReact;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotypeForsale;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FDemandsService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.CookieUtils;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.dingpeikeji.quickdeer.utils.JsonUtils;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.google.common.collect.Lists;
import com.tencent.WXPay;
import com.tencent.common.Configure;
import com.tencent.protocol.refund_protocol.RefundReqData;

/**
 * 政务版登录
 * 
 * @author lh
 */
@Controller
@RequestMapping(value = "${govPath}")
public class GovLoginController extends BaseController {
	public static final String GOV_USER_IN_SESSION = "gov_user";
	@Autowired
	private FrontUserService userService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private FDemandsService demandsService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private FRealscheService fRealscheService;
	@Autowired
	private TRealscheService tRealscheService;
	@Autowired
	private TOrdersOutService tOrdersOutService;
	@Autowired
	private TRcptService tRcptService;
	@Autowired
	private TOrdersService ordersService;
	@Autowired
	private TUsersRcptService tUsersRcptService;
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private SystemService systemService;
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private TRentgroupService tRentgroupService;

	private static String TODAY;
	private static String TOMORROW;
	private static String MAXDAY;
	private static String TIME = "06:00";// 默认时间

	// 限制时间选择范围
	public static void initDate(Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		TODAY = sdf.format(calendar.getTime());
		calendar.add(Calendar.DAY_OF_YEAR, +1);
		TOMORROW = sdf.format(calendar.getTime());
		calendar.add(Calendar.MONTH, +3);
		MAXDAY = getSpecifiedDayBefore(sdf.format(calendar.getTime()));
		model.addAttribute("today", TODAY);
		model.addAttribute("tomorrow", TOMORROW);
		model.addAttribute("maxDay", MAXDAY);
		model.addAttribute("time", TIME);
	}

	public static long getDatePoor(Date endDate, Date nowDate) {

		long nh = 1000 * 60 * 60;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - nowDate.getTime();
		// 计算差多少小时
		long hour = diff / nh;
		return hour;
	}

	public static String getSpecifiedDayBefore(String specifiedDay) {
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);
		String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
		return dayBefore;
	}

	// 登录页面
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, Model model) throws Exception {
		initDate(model);
		model.addAttribute("pageStyle", "customRent");// 菜单选中
		return "gov/index/login";
	}

	// 时间选择默认时间
	private static Date defaultTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 9);
		calendar.set(Calendar.MINUTE, 0);
		return calendar.getTime();
	}

	// 登陆成功显示的页面,定制包车
	@RequestMapping(value = "/customRent")
	public String customRent(HttpServletRequest request, Model model, TDemands tDemands, RedirectAttributes redirectAttributes) throws Exception {
		initDate(model);
		tDemands.setFromdate(defaultTime());
		// 车型数据
		List<TCargotype> cargotypeList = tCargotypeService.findList(new TCargotype());
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = userService.get(a.getId());
		model.addAttribute("tel", user.getMobile());
		model.addAttribute("cargotypeList", cargotypeList);
		model.addAttribute("pageStyle", "customRent");
		model.addAttribute("tDemands", tDemands);
		return "gov/customerRent/customRent";
	}

	// 定制包车填写
	@RequestMapping(value = "/saveDemand")
	public String saveDemand(TDemands tDemands, HttpServletRequest request, RedirectAttributes redirectAttributes,
			TCargotype cargotype, HttpServletResponse response, Model model) {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		initDate(model);
		model.addAttribute("defaultTime", defaultTime());
		if(getDatePoor(tDemands.getFromdate(),new Date())<2||getDatePoor(tDemands.getFromdate(),new Date())>2160){
			redirectAttributes.addFlashAttribute("message", "请选择2小时之后且3个月之内的时间");
			return "redirect:customRent";
		}
		String siteid = tSitedtlService.getSiteIdByName(request.getParameter("departcity.sitename"));
		TSitedtl tSitedtl = tSitedtlService.get(siteid);
		tDemands.setDepartcity(tSitedtl);
		if (siteid == null || "".equals(siteid) || "null".equals(siteid) || "null\n".equals(siteid)) {
			redirectAttributes.addFlashAttribute("message", "暂不支持此地区定制包车业务");
			return "redirect:customRent";
		}
		String fromdateStr = request.getParameter("fromdate");
		tDemands.setFromdateStr(fromdateStr);
		tDemands.setFromdate(DateUtils.parseDate(fromdateStr));
		tDemands.setReactstatus(TDemands.REACTSTATUS_WAIT);
		// 根据传入的cartypeid获取对应的车型

		TCargotype tCargotype = tCargotypeService.get(cargotype.getCargotypeid().toString());
		tDemands.setCartype(tCargotype);
		if (tDemands.getDemandid() == null) {

			User user = userService.get(a.getId());
			if (user == null) {
				redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
				return "redirect:index";
			}
			tDemands.setCreateBy(user);
			tDemands.setCreateDate(new Date());
		}
		demandsService.save(tDemands);

		User user = userService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		tDemands.setCreateBy(user);
		Page<TDemands> page = demandsService.findPage(new Page<TDemands>(request, response), tDemands);
		model.addAttribute("page", page);
		return "gov/customerRent/myCustomRent";
	}

	// 定制包车,我的需求
	@RequestMapping(value = "/myCustomRent")
	public String myCustomRent(TDemands tDemands, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = userService.get(a.getId());
		tDemands.setCreateBy(user);
		Page<TDemands> page = demandsService.findPage(new Page<TDemands>(request, response), tDemands);
		model.addAttribute("page", page);
		return "gov/customerRent/myCustomRent";
	}

	// 定制包车,查看
	@RequestMapping(value = "/checkCustomRent")
	public String checkCustomRent(TDemands tDemands, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		String demandid = tDemands.getDemandid() + "";
		if (StringUtil.isNotEmpty(demandid)) {
			tDemands = demandsService.get("" + tDemands.getDemandid());
			String address = demandsService.getSendAddress(demandid);
			if (StringUtils.isEmpty(address)) {
				address = "";
			}
			tDemands.setSendAddress(address);
			List<DemandsReact> demandsReactList = demandsService.findDemandsReactList(tDemands);
			if (demandsReactList != null && demandsReactList.size() > 0) {
				for (DemandsReact dr : demandsReactList) {
					dr.setImages((tDemands.getCartype().getImages()));// 设置图片
				}
				model.addAttribute("reactList", demandsReactList);
			}
			model.addAttribute("tDemands", tDemands);
		}
		return "gov/customerRent/customInfo";
	}

	// 定制包车-确认支付
	@RequestMapping(value = "/submitCustomOrder")
	public String submitCustomOrder(TOrders orders, TDemands tDemands, Integer reactid, Model model,
			RedirectAttributes redirectAttributes, HttpServletRequest request) throws ParseException {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = userService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		orders.setOrderuserid(a.getId());
		List<String> messages = Lists.newArrayList(); // 消息
		DemandsReact react = demandsService.getDemandsReact(reactid);
		TDemands demand = new TDemands();
		if (messages.isEmpty()) {
			demand = demandsService.get(react.getDemandid() + "");
			if (!TDemands.REACTSTATUS_SURE.equals(demand.getReactstatus())) {
				messages.add("该定制需求不可支付");
			}
		}
		if (StringUtil.isNotBlank(demand.getOrderid())) {// 已经生成了订单
			// 删除原来的订单
			tOrdersService.delOrderById(demand.getOrderid());
		}
		if (messages.isEmpty()) {
			orders.setDueamount("" + react.getPrice());
			orders.setRealscheid(reactid + "");
			orders.setPurchasenum(tDemands.getVehiclenum() + "");
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid + "");
					model.addAttribute("orders", orders);
					// 修改demand表里的orderid
					demandsService.updateOrderId(orderid + "", demand.getDemandid());
					model.addAttribute("demand", demand);
					return "gov/customerRent/customPay";
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("message", messages.get(0));
		return "redirect:myCustomRent";
	}

	// 定制包车,取消
	@RequestMapping(value = "/cancelCustomRent")
	public String cancelCustomRent(TDemands tDemands, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = userService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		tDemands.setCreateBy(user);
		demandsService.cancel(tDemands);
		return "redirect:myCustomRent";
	}

	// 定制包车,提交生成订单
	@RequestMapping(value = "/submitDemandOrder")
	public String submitDemandOrder(CuponsInfo cuponsInfo, TOrders orders, TDemands tDemands, Integer reactid,
			HttpServletRequest request, RedirectAttributes redirectAttributes, HttpServletResponse response,
			Model model) throws ParseException {

		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		orders.setOrderuserid(user.getId());

		List<String> messages = Lists.newArrayList(); // 消息
		DemandsReact react = demandsService.getDemandsReact(reactid);
		TDemands demand = new TDemands();
		if (messages.isEmpty()) {
			demand = demandsService.get(react.getDemandid() + "");
			if (!TDemands.REACTSTATUS_SURE.equals(demand.getReactstatus())) {
				messages.add("该定制需求不可支付");
			}
		}
		if (StringUtil.isNotBlank(demand.getOrderid())) {// 已经生成了订单
			// 删除原来的订单
			tOrdersService.delOrderById(demand.getOrderid());
		}
		if (messages.isEmpty()) {
			orders.setDueamount("" + react.getPrice());
			orders.setRealscheid(reactid + "");
			orders.setPurchasenum(tDemands.getVehiclenum() + "");
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid + "");
					// map.put("orders", orders);
					// //修改demand表里的orderid
					// demandsService.updateOrderId(orderid+"",demand.getDemandid());
					// return BackResult.ok(map);
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("message", messages.get(0));
		return "redirect:myCustomRent";
	}

	// 按天包车
	@RequestMapping(value = "/dayRent") 
	public String dayRent(HttpServletRequest request, Model model) throws Exception {
		initDate(model);
		model.addAttribute("defaultTime", defaultTime());
		model.addAttribute("pageStyle", "dayRent");
		return "gov/dayRent/dayRent";
	}

	// 按天包车填写
	@RequestMapping(value = "/getDayRentList")
	public String getDayRentList(TRentproduct tRentproduct, RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response, Model model, TCargotype tCargotype, String pageNo,
			String pageSize) throws Exception {
		// 日期处理
		initDate(model);
		model.addAttribute("defaultTime", defaultTime());
		String fromdate = request.getParameter("fromdateStr");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		if(getDatePoor(sdf.parse(fromdate),new Date())<2||getDatePoor(sdf.parse(fromdate),new Date())>2160){
			redirectAttributes.addFlashAttribute("message", "请选择2小时之后且3个月之内的时间");
			return "redirect:dayRent";
		}
		String[] arr = fromdate.split("\\s");
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 获取车型
		tCargotype.setTstyles(request.getParameter("tstyle"));
		model.addAttribute("tstyle", request.getParameter("tstyle"));
		tRentproduct.setCargotype(tCargotype);
		// 如果发车日期为空或者小于当前日期，则设置成明天 包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		// 分页对象
		Page<TCargotype> page = new Page<TCargotype>(request, response);
		tCargotype.setPage(page);
		if(pageNo ==null||pageSize==null){
			page.setPageSize(15);
			page.setPageNo(1);
		}else{
			page.setPageSize(Integer.parseInt(pageSize));
			page.setPageNo(Integer.parseInt(pageNo));
		}
		// 跨市range=2,市内range=1(t_rentgroup表)
		if (tRentproduct.getTabType().equals("市内")) {
			tCargotype.setRange("1");
		} else {
			tCargotype.setRange("2");
		}
		List<TCargotype> cargotypeList = rentproductService.findCargotypeList(tCargotype);
		page.setList(cargotypeList);
		// 获取车型id,查询对应的线路报价
		List<TRentproduct> rentproductList = null;
		if (cargotypeList.size() > 0) {
			for (TCargotype tc : cargotypeList) {
				double min = 9999999;
				tRentproduct.setCargotype(tc);
				// 市内日租包车
				// TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType())&&
				if (tRentproduct.getTabType().equals("市内")) {
					rentproductList = rentproductService.findInCityList(tRentproduct);
					if (tRentproduct.getDaysnum() == 0) {// 0.5天,计算价格
						for (TRentproduct rp : rentproductList) {
							rp.setSuitrtnprice(Math.rint(rp.getSuitrtnprice() * 0.8));
						}

					}
				}
				// 跨城日租包车TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType())&&
				if (tRentproduct.getTabType().equals("跨市")) {
					rentproductList = rentproductService.findBetweenCityList(tRentproduct);
				}

				for (TRentproduct rent : rentproductList) {
					if (min > rent.getSuitrtnprice()) {
						min = rent.getSuitrtnprice();
					}
				}
				tc.setLowestAirPrice(min);
				tc.setRentproductList(rentproductList);
			}
			model.addAttribute("page", page);
			tRentproduct.setFromdateStr(fromdate);
			model.addAttribute("tRentproduct", tRentproduct);
			model.addAttribute("cargotypeList", cargotypeList);
			model.addAttribute("totalCount", page.getCount() + "");
			return "gov/dayRent/dayRentResult";
		} else {
			redirectAttributes.addFlashAttribute("message", "未查询到数据");
			tRentproduct.setFromdateStr(fromdate);
			model.addAttribute("tRentproduct", tRentproduct);
			model.addAttribute("cargotypeList", cargotypeList);
			model.addAttribute("totalCount", page.getCount() + "");
			return "gov/dayRent/dayRentResult";
		}
	}

	// 按天包车订单提交
	@RequestMapping(value = "/dayRentDetails")
	public String dayRentDetails(String images, TRentproduct tRentproduct, RedirectAttributes redirectAttributes,
			Model model, HttpServletRequest request) throws Exception {

		String viewPage = "gov/dayRent/dayRentSubmit"; // 视图
		
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = userService.get(a.getId());
		model.addAttribute("tel", user.getMobile());
		// 根据ID查询选中的整车信息
		String[] arr = tRentproduct.getFromdateStr().split("\\s");
		model.addAttribute("times", tRentproduct.getFromdateStr());
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.get(rentproduct.getRentgrpid());
		if (rentproduct != null) {

			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(tRentproduct.getRentid());
			query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr()));

			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			rentproduct.setSuitrtnprice(query.getSuitrtnprice());
			if(tRentproduct.getDaysnum() == 0){
				rentproduct.setSuitrtnprice(Math.round(0.8*query.getSuitrtnprice())+0.0);
			}
		}

		// 数据校验

		// 消息集合
		List<String> messages = Lists.newArrayList();
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);

		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}

		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}

		if (!messages.isEmpty()) {
			addMessage(model, messages.toArray(new String[] {}));
		}
		
		
		model.addAttribute("images", images);
		model.addAttribute("tRentproduct", rentproduct);
		model.addAttribute("rentgroup", rentgroup);
		model.addAttribute("query", tRentproduct);
		String format = MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return format;

	}

	// 按天包车订单提交
	@RequestMapping(value = "/submitDayRentOrder")
	public String submitDayRentOrder(TOrders orders, RedirectAttributes redirectAttributes, Model model,
			HttpServletRequest request) throws Exception {
		User user = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		orders.setOrderuserid(user.getId());
		
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		TRentproduct tRentproduct = new TRentproduct();
		// 手机端传入日期格式 2000-01-01 06:00
		String fromdateStr = request.getParameter("fromdateStr");
		orders.setDepartdateStr(fromdateStr);
		String[] arr = fromdateStr.split("\\s");// 按空格切割
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		if (messages.isEmpty()) {
			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));
			orders.setDepartdate(query.getDepartdate());// Fri Aug 25 06:00:00
														// CST 2017
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			Double suitrtnprice = query.getSuitrtnprice();
			if (orders.getBookingdays() == 0) {
				suitrtnprice = Math.rint(suitrtnprice * 0.8);// 四舍五入取整
			}
			orders.setDueamount("" + suitrtnprice);
			orders.setDepartcity(request.getParameter("departcity.sitename"));
			Integer purchasenum = Integer.valueOf(orders.getPurchasenum());
			if (orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_DAY)) {
				if (orders.getBookingdays() == 0) {
					orders.setDueamount("" + Math.rint(query.getSuitrtnprice() * 0.8 * 1 * purchasenum));
				} else {
					orders.setDueamount("" + query.getSuitrtnprice() * orders.getBookingdays() * purchasenum);
				}
			} else {
				orders.setDueamount("" + query.getSuitrtnprice() * purchasenum);
			}

			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid + "");
					model.addAttribute("orders", orders);
					return "gov/dayRent/dayRentPay";
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("message", messages.get(0));
		return "redirect:dayRent";
	}

	// 接送机
	@RequestMapping(value = "/airRent")
	public String airRent(HttpServletRequest request, Model model) throws Exception {
		initDate(model);
		model.addAttribute("defaultTime", defaultTime());
		model.addAttribute("pageStyle", "airRent");
		return "gov/airRent/airRent2";
	}

	// 接送机查询
	@RequestMapping(value = "/airRentList")
	public String getAirList(TRentproduct tRentproduct, HttpServletRequest request,
			RedirectAttributes redirectAttributes, HttpServletResponse response, Model model,
			TCargotypeForsale cargotypeForsale ,String pageNo,String pageSize) throws Exception {
		initDate(model);
		model.addAttribute("defaultTime", defaultTime());
		// 手机端传入日期格式 2000-01-01 06:00
		String fromdateStr = request.getParameter("fromdateStr");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		if(getDatePoor(sdf.parse(fromdateStr),new Date())<2||getDatePoor(sdf.parse(fromdateStr),new Date())>2160){
			redirectAttributes.addFlashAttribute("message", "请选择2小时之后且3个月之内的时间");
			return "redirect:airRent";
		}
		String[] arr = fromdateStr.split("\\s");// 按空格切割
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 如果发车日期为空或者小于当前日期，则设置成明天
		// 包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		String destSiteName = request.getParameter("destcity.sitename");// 目的地
		String detailAddress = request.getParameter("aboardAddress");// 详细地址
		// 获取车型
		TCargotype cargotype = new TCargotype();
		String tstyle = request.getParameter("tstyle");
		model.addAttribute("tstyle", tstyle);
		cargotypeForsale.setCargotype(cargotype);
		cargotypeForsale.getCargotype().setTstyles(tstyle);
		// 百度地图自动赋值城市名称,根据名称查询
		TSitedtl sitedtl = tSitedtlService.getDestCityByName(tRentproduct.getDestcity().getSitename());
		if (sitedtl != null) {
			tRentproduct.setDestcity(sitedtl);// 不匹配,重新赋值
			cargotypeForsale.setDepartcity(tRentproduct.getDepartcity());
			cargotypeForsale.setDestcity(tRentproduct.getDestcity());
		} else {
			tRentproduct.setDestcity(null);// 查询不到目的地
			cargotypeForsale.setDepartcity(tRentproduct.getDepartcity());
			cargotypeForsale.setDestcity(tRentproduct.getDestcity());
		}
		// 产品名称
		String productName = "";
		if (tRentproduct.getDestcity() != null) {
			productName = tRentproduct.getDepartcity().getSitename() + "-" + tRentproduct.getDestcity().getSitename()
					+ "(" + tRentproduct.getTabType() + ")";
		} else {
			productName = tRentproduct.getDepartcity().getSitename() + "-" + destSiteName + "("
					+ tRentproduct.getTabType() + ")";
		}
		tRentproduct.setProductname(productName);
		tRentproduct.setAboardAddress(detailAddress);
		String kms = tRentproduct.getMapkm();// 地图测算的距离
		double distance = 0.0;
		int disLevel = 0;
		if (StringUtils.isNotEmpty(kms)) {
			if (kms.indexOf("公里") != -1) {
				distance = Double.parseDouble(kms.substring(0, kms.indexOf("公里")));
				if (distance <= 50 && distance >= 0) {
					disLevel = 1;
				} else if (distance <= 150 && distance > 50) {
					disLevel = 2;
				} else if (distance <= 275 && distance > 150) {
					disLevel = 3;
				} else {
					disLevel = 4;
				}
			} else {
				disLevel = 1;// 距离太近,取不到公里数
			}
		}

		// 根据出发地,目的地 查询所有车型
		Page<TCargotypeForsale> page = new Page<TCargotypeForsale>(request, response);
		if(pageNo ==null||pageSize==null){
			page.setPageSize(15);
			page.setPageNo(1);
		}else{
			page.setPageSize(Integer.parseInt(pageSize));
			page.setPageNo(Integer.parseInt(pageNo));
		}
		cargotypeForsale.setPage(page);
		List<TCargotypeForsale> cargotypeList = rentproductService.findAirCargotypeList(cargotypeForsale);
		page.setList(cargotypeList);
		List<Office> officeList = null;
		// 根据车型获取对应的车队
		if (cargotypeList.size() > 0 && cargotypeList != null) {
			for (TCargotypeForsale tc : cargotypeList) {
				double condition0 = ((tc.getCargotype().getNudePrice() / 2.00 + 100)
						+ (tc.getCargotype().getOilcost() + tc.getCargotype().getRoadmodules()) * distance * 2);
				double condition1 = (tc.getCargotype().getNudePrice()
						+ (tc.getCargotype().getOilcost() + tc.getCargotype().getRoadmodules()) * distance * 2);
				Set<Double> priceSet = new TreeSet<Double>();
				List<Double> priceList = new ArrayList<Double>();
				tc.setDepartcity(tRentproduct.getDepartcity());
				tc.setDestcity(tRentproduct.getDestcity());
				tc.setDisLevel(disLevel);// 距离等级
				officeList = rentproductService.findAirProductByType(tc);
				if (officeList.size() > 0 && officeList != null) {
					for (Office office : officeList) {
						if (distance <= 50 && distance >= 0) {
							office.setSuitrtnprice(Math.ceil(condition0 * office.getFactor()));
						} else {
							office.setSuitrtnprice(Math.ceil(condition1 * office.getFactor()));
						}
					}
				}
				tc.setOfficeList(officeList);
				// 取最低价
				for (Office office : officeList) {
					priceSet.add(office.getSuitrtnprice());
				}
				for (Double double1 : priceSet) {
					priceList.add(double1);
				}
				if (priceList.size() > 0) {
					tc.setLowestAirPrice(priceList.get(0));
				}
			}
		} else {
			redirectAttributes.addFlashAttribute("message", "未查询到数据");
			tRentproduct.setFromdateStr(fromdateStr);
			model.addAttribute("rentproductList", cargotypeList);
			model.addAttribute("totalCount", page.getCount());
			model.addAttribute("tRentproduct", tRentproduct);
			return "gov/airRent/airRentList";
		}
		model.addAttribute("page", page);
		tRentproduct.setFromdateStr(fromdateStr);
		model.addAttribute("rentproductList", cargotypeList);
		model.addAttribute("totalCount", page.getCount());
		model.addAttribute("tRentproduct", tRentproduct);
		return "gov/airRent/airRentList";
	}

	// 接送机详情
	@RequestMapping("airdetails")
	public String airDetails(TRentproduct tRentproduct, Model model, HttpServletRequest request,
			RedirectAttributes redirectAttributes,HttpServletResponse response) throws Exception {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		// 根据车队abbr和name查询车队id
		String id = officeService.findIdByNameAndAbbr(tRentproduct.getOffice().getName(),tRentproduct.getOffice().getAbbr());
		User user = frontUserService.get(a.getId());
		tRentproduct.getOffice().setId(id);
		model.addAttribute("tel", user.getMobile());
		model.addAttribute("tRentproduct", tRentproduct);
		return "gov/airRent/airRentSubmit";
	}

	// 接送机提交
	@RequestMapping("submitAirRentOrder")
	public String submitAirRentOrder(TOrders orders, String totalPrice, Model model,
			RedirectAttributes redirectAttributes, HttpServletRequest request, TRentproduct tRentproduct)
			throws Exception {
		User user = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		String id = officeService.findIdByAbbr(request.getParameter("office.name"));
		tRentproduct.getOffice().setId(id);
		// 接收出发地,目的地
		String departcitySitename = request.getParameter("departcity.sitename");
		String destcitySitename = request.getParameter("destcity.sitename");
		orders.setDepartcity(departcitySitename);
		orders.setDestcity(destcitySitename);
		orders.setBookingdays(1);// 接送机默认一天
		orders.setOrderuserid(user.getId());
		orders.setCargotypeid(tRentproduct.getCargotype().getCargotypeid());
		orders.getOffice().setId(id);
		// 查询realscheid,自增加1
		int realscheid = rentproductService.findLastRealscheidFromOrder();
		orders.setRealscheid((realscheid + 1) + "");
		// 设置价格
		orders.setDueamount(totalPrice);
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		// 处理时间
		orders.setDepartdateStr(request.getParameter("fromdateStr"));
		if (messages.isEmpty()) {
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				@SuppressWarnings("unused")
				boolean success = pro.success();
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid + "");
					model.addAttribute("orders", orders);
					return "gov/airRent/airRentPay";
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("message", messages.get(0));
		return "redirect:airRent";
	}

	// 我的订单
	@RequestMapping(value = "/orderList")
	public String orderList(TOrders orders, RedirectAttributes redirectAttributes, HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		initDate(model);
		// 当前订票人
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		orders.setOrderuserid(user.getId());
		Page<TOrders> page = fRealscheService.findOrderPageForMobile(new Page<TOrders>(request, response), orders);
		if (page.getCount() == 0) {
			redirectAttributes.addFlashAttribute("message", "未查询到订单数据");
		}
		model.addAttribute("page", page);
		model.addAttribute("pageStyle", "orderList");
		return "gov/order/orderList";
	}

	// 订单详情
	@RequestMapping(value = "/checkOrder")
	public String getOrderDetail(TOrders orders, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) {
		orders = fRealscheService.getOrders(orders.getOrderid());
		if (orders == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到数据");
			return null;
		}
		if (orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_CUSTOM)
				&& !orders.getOrderstatus().equals(TOrders.STATUS_BACK)
				&& !orders.getOrderstatus().equals(TOrders.STATUS_CANCEL)) {
			TRealsche realsche = tRealscheService.get(orders.getRealscheid());
			if (realsche != null) {
				DemandsReact react = demandsService.getDemandsReact(Integer.parseInt(realsche.getScheid()));
				TDemands tDemands = demandsService.getDemandById(react.getDemandid());
				model.addAttribute("react", react);
				model.addAttribute("tDemands", tDemands);
			}
		} else {
			model.addAttribute("cargotype", orders.getCartype());
		}
		if (orders.getUseCupons().equals("1")) {
			model.addAttribute("cuponsInfo", tCuponsService.getRecordByOrderId(orders.getOrderid()));
		}
		model.addAttribute("orders", orders);
		return "gov/order/orderDetail";
	}

	// 订单取消
	@RequestMapping(value = "/cancelOrder")
	public String cancelOrder(TOrders orders, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) {
		String cancelid = null; // 取消人ID
		TOrders ord = tOrdersService.get(orders.getOrderid());
		if (!ord.getOrderstatus().equals(TOrders.STATUS_NO_PAY)) {
			redirectAttributes.addFlashAttribute("message", "该订单不能取消");
			return "redirect:orderList";
		} else {
			String message = fRealscheService.cancelOrder(orders, cancelid);
			if (message == null) {
				redirectAttributes.addFlashAttribute("message", "取消订单成功！");
				return "redirect:orderList";
			} else {
				return "redirect:orderList";
			}
		}
	}

	// 订单支付
	@RequestMapping(value = "/payOrder")
	public String payOrder(TOrders orders, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) {
		TOrders ord = tOrdersService.get(orders.getOrderid());
		model.addAttribute("orders", ord);
		return "gov/order/orderPay";
	}

	// 订单退单
	@RequestMapping(value = "/orderBack")
	public String orderBack(TOrders orders, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		String orderid = request.getParameter("orderid");
		TOrders torders = fRealscheService.getOrders(orderid);
		if (torders.getDepartdate().before(new Date())) {
			redirectAttributes.addFlashAttribute("message", "已过发车时间,无法退单");
			return "redirect:orderList";
		}
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = userService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		// 计算时间差
		long dateDistance = getDatePoor(torders.getDepartdate(), new Date());
		// 计算违约金
		double penalty = 0.0;
		if (dateDistance <= 24) {
			// 行程开始前 24 小时内,按费用总额的50%收取违约金
			penalty = Math.ceil(Double.parseDouble(torders.getDueamount()) * 0.5);
		} else if (dateDistance <= 0) {
			// 超过发车时间不可退款
			penalty = Math.ceil(Double.parseDouble(torders.getDueamount()));
		} else if (dateDistance <= 72 && dateDistance > 24) {
			// 行程开始前 72 小时至 24 小时,按费用总额的30%(普通用户)
			if (Office.FLAT_TYPE_SMALLCO.equals(user.getOffice().getFlatType())) {
				penalty = Math.ceil(Double.parseDouble(torders.getDueamount()) * 0.3);
			} else {// 旅行商10%
				penalty = Math.ceil(Double.parseDouble(torders.getDueamount()) * 0.1);
			}
		} else {
			penalty = 0.0;
		}
		torders.setPenalty(penalty);
		model.addAttribute("orders", torders);
		model.addAttribute("price", Double.parseDouble(torders.getDueamount()) - penalty);
		return "gov/order/orderBack";
	}

	// 退单提交
	@RequestMapping(value = "/backMoney")
	public String backMoney(TOrders orders, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		TOrders torders = fRealscheService.getOrders(orders.getOrderid());
		// ==========>>数据校验
		List<String> messages = Lists.newArrayList(); // 消息
		boolean sendSms = false; // 是否发送短信
		if (messages.isEmpty()) {
			TPayinfo payinfo = torders.getPayinfo();
			if (payinfo != null && payinfo.getDiscountid() != null) {
				Map<String, Object> result = fRealscheService.proCmptReturn(orders);
				Integer returnflag = (Integer) result.get("returnflag");
				if (returnflag != null && returnflag == 0) {
					String payway = torders.getPayway();
					// 批次号，必填，格式：当天日期[8位]+序列号[3至24位]，如：201603081000001
					String batch_no = new SimpleDateFormat("yyyyMMdd").format(new Date())
							+ UUID.randomUUID().toString().replace("-", "").substring(0, 16);
					// 退款笔数，必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
					String batch_num = "1";
					Double money = (Double) result.get("returnmoney");
					// 退款详细数据，必填，格式（支付宝交易号^退款金额^备注），多笔请用#隔开
					String detail_data = payinfo.getFlowno() // 流水号就是支付宝单号
							+ "^" + money + "^" + torders.getPurchasenum() + "," + torders.getChildnum(); // 退款数量
					if (payway.equals(TOrders.PAY_WAY_ALIPAY)) { // 支付宝支付
						String refund_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						try {
							RefundFastpayByPlatformNopwdReq req = new RefundFastpayByPlatformNopwdReq(batch_no,
									refund_date, batch_num, detail_data);
							new RefundFastpayByPlatformNopwdApi().execute(req, request, response);
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(torders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(torders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(
									Integer.parseInt(torders.getChildnum() == null ? "0" : torders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmRtn(batch_no);
							messages.add("支付宝退票请求成功！");
							sendSms = true;
						} catch (Exception e) {
							redirectAttributes.addFlashAttribute("message", "请求退款异常！");
							return "redirect:orderList";
						}
					}
					if (payway.equals(TOrders.PAY_WAY_WXPAY)) { // 微信支付
						String out_trade_no = "";
						for (int i = 0; i < 32 - orders.getOrderid().length(); i++) { // 补齐32位字符串
							out_trade_no += "0";
						}
						int moneyint = (int) (money * 100);
						out_trade_no += torders.getOrderid();
						RefundReqData refundReqData = new RefundReqData(""// payinfo.getFlowno()
								, out_trade_no, "", batch_no, (int) (Double.valueOf(torders.getDueamount()) * 100),
								moneyint, Configure.getMchid(), "CNY");
						try {
							if (moneyint != 0) {
								String responseString = WXPay.requestRefundService(refundReqData);
								logger.debug("微信退款返回信息：{}", responseString);
							}
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(torders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(torders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(
									Integer.parseInt(torders.getChildnum() == null ? "0" : torders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmRtn(batch_no);
							if (moneyint == 0) {
								redirectAttributes.addFlashAttribute("message", "收取手续费后，可退费用为0元！");
							} else {
								redirectAttributes.addFlashAttribute("message", "微信退票请求成功！");
							}
							sendSms = true;
						} catch (Exception e) {
							logger.debug("微信退票异常信息", e);
							redirectAttributes.addFlashAttribute("message", "请求退款异常！");
							return "redirect:orderList";
						}
					}
				} else {
					messages.add((String) result.get("returnmsg"));
				}
			} else {
				redirectAttributes.addFlashAttribute("message", "订单暂未生效！");
				return "redirect:orderList";
			}
		}
		// 订车人申请退单成功后，收到平台短信
		if (sendSms) {
			Sms sms = new Sms();
			sms.setMobile(torders.getPayertel());
			sms.setContent("【霞客约车】您购买的由" + torders.getOffice().getName() + "提供的用车订单（" + torders.getOrderid()
					+ "）已取消，我们将根据预订规则将相应款项在3个工作日内返回您的支付账户。");
			try {
				SmsApi.sendSms(sms);
				return "redirect:orderList";
			} catch (Exception e) {
			}
		}
		return "redirect:orderList";
	}

	// 发票管理
	@RequestMapping(value = "/rcptList")
	public String rcptList(HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model, String pageNo, String pageSize) throws Exception {
		initDate(model);
		TOrders orders = new TOrders();
		// 当前订票人
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		orders.setOrderuserid(user.getId());
		orders.setOrderstatus(TOrders.STATUS_PAY);
		orders.setGenRcpt("no"); // 未开发票
		Page<TOrders> page = new Page<TOrders>(request, response);
		// page.setPageNo(Integer.parseInt(pageNo));
		// page.setPageSize(Integer.parseInt(pageSize));
		page = ordersService.findPage(new Page<TOrders>(request, response), orders);
		if (page.getCount() == 0) {
			redirectAttributes.addFlashAttribute("message", "暂未有可开发票订单");
			return "gov/rcpt/rcptList";
		}
		model.addAttribute("page", page);
		model.addAttribute("pageStyle", "rcptList");
		return "gov/rcpt/rcptList";
	}

	// 开票记录
	@RequestMapping(value = "/rcptRecord")
	public String rcptRecord(TUsersRcpt tUsersRcpt, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model, String pageNo, String pageSize) {
		// 当前订票人
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		TRcpt rcpt = new TRcpt();
		rcpt.setCreateBy(user);
		// page.setPageNo(Integer.parseInt(pageNo));
		// page.setPageSize(Integer.parseInt(pageSize));
		Page<TRcpt> page = tRcptService.findPage(new Page<TRcpt>(request, response), rcpt);
		if (page.getCount() == 0) {
			redirectAttributes.addFlashAttribute("message", "未查询到开票记录");
			return "gov/rcpt/rcptRecord";
		}
		 List<TRcpt> list = page.getList();
		 for (TRcpt tr : list) {
		 double parseDouble = tr.getTotalOutkmsfee();
		 double parseDouble2 = tr.getTotalOuttimefee();
		 double parseDouble3 = tr.getTotalRirverfee();
		 double parseDouble4 = tr.getRcptamount();
		 double total = parseDouble+parseDouble2+parseDouble3+parseDouble4;
		 tr.setTotalPrice(total+"");//发票总金额
		 }
		model.addAttribute("page", page);
		return "gov/rcpt/rcptRecord";
	}

	// 开票信息查看
	@RequestMapping(value = "/userRcptInfo")
	public String userRcptInfo(TUsersRcpt tUsersRcpt, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model, String money,String rcptIds,String totalOuttimefee,String totalOutkmsfee,String totalRirverfee) {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		tUsersRcpt = tUsersRcptService.getByUserid(user.getId());
		if (tUsersRcpt == null || tUsersRcpt.getAlwaysid() == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到数据");
			return "gov/rcpt/rcptInfo";
		}
		model.addAttribute("tUsersRcpt", tUsersRcpt);
		if (money != null && money.trim().length() > 0) {
			model.addAttribute("totalOuttimefee", totalOuttimefee);
			model.addAttribute("totalOutkmsfee", totalOutkmsfee);
			model.addAttribute("totalRirverfee", totalRirverfee);
			model.addAttribute("money", money);
			model.addAttribute("rcptIds", rcptIds);
			return "gov/rcpt/rcptInfoSubmit";
		}
		return "gov/rcpt/rcptInfo";
	}

	// 开票信息保存
	@RequestMapping(value = "/saveUserRcptInfo")
	public String saveUserRcptInfo(TUsersRcpt tUsersRcpt, HttpServletRequest request,
			RedirectAttributes redirectAttributes, HttpServletResponse response, Model model) {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		if (StringUtils.isBlank(tUsersRcpt.getUserid())) {
			tUsersRcpt.setUserid(user.getId());
		}
		TUsersRcpt usersRcpt = tUsersRcptService.getByUserid(user.getId());
		tUsersRcpt.setRcpttype("1");
		tUsersRcpt.setAlwaysid(usersRcpt.getAlwaysid());
		tUsersRcptService.save(tUsersRcpt);
		model.addAttribute("tUsersRcpt", tUsersRcpt);
		return "redirect:rcptList";
	}
	
	

	// 开票提交
	@RequestMapping(value = "/saveRcpt")
	public String saveRcpt(TUsersRcpt tUsersRcpt, String rcptIds, String outkmsfee, String outtimefee, String dirverfee,
			HttpServletRequest request, RedirectAttributes redirectAttributes, HttpServletResponse response,
			Model model) {
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		if (StringUtils.isBlank(tUsersRcpt.getUserid())) {
			tUsersRcpt.setUserid(user.getId());
		}
		// 获取总的超公里费
		String[] kmsArr = outkmsfee.split(",");
		double totalKmsFee = 0D;
		if (kmsArr.length > 0) {
			for (String km : kmsArr) {
				totalKmsFee += Double.parseDouble(km);
			}
		}
		tUsersRcpt.setTotalOutkmsfee(totalKmsFee);
		// 获取总的超时长费
		String[] timeArr = outtimefee.split(",");
		double totalTimeFee = 0D;
		if (timeArr.length > 0) {
			for (String tm : timeArr) {
				totalTimeFee += Double.parseDouble(tm);
			}
		}
		tUsersRcpt.setTotalOuttimefee(totalTimeFee);
		// 获取总的司机费用
		String[] driverArr = dirverfee.split(",");
		double totalDriverFee = 0D;
		if (driverArr.length > 0) {
			for (String da : driverArr) {
				totalDriverFee += Double.parseDouble(da);
			}
		}
		tUsersRcpt.setTotalRirverfee(totalDriverFee);
		tUsersRcpt.setRcpttype("1");
		tUsersRcptService.save(tUsersRcpt);
		if (StringUtils.isNotBlank(rcptIds)) {
			TUsersRcpt ur = tUsersRcptService.getByUserid(user.getId());
			ur.setTotalOutkmsfee(totalKmsFee);
			ur.setTotalOuttimefee(totalTimeFee);
			ur.setTotalRirverfee(totalDriverFee);
			if (ur.getAlwaysid() == null) {
				redirectAttributes.addFlashAttribute("message", "请先填写发票信息！");
				return "redirect:rcptList";
			}
			this.tUsersRcptService.genRcpts(rcptIds, ur, user);
			redirectAttributes.addFlashAttribute("message", "提交用户发票信息成功");
			return "redirect:rcptList";

		}
		return "redirect:rcptList";
	}

	// 个人中心
	@RequestMapping(value = "/personal")
	public String personal(HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		initDate(model);
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		User user = frontUserService.get(a.getId());
		if (user == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		model.addAttribute("nick", user.getName());
		model.addAttribute("email", user.getEmail());
		model.addAttribute("mobile", user.getMobile());
		return "gov/personal/personal";
	}

	// 个人中心
	@RequestMapping(value = "/savePersonal")
	public String savePersonal(User user, HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		initDate(model);
		User a = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (a == null) {
			redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
			return "redirect:index";
		}
		a.setName(user.getName());
		a.setEmail(user.getEmail());
		a.setMobile(user.getMobile());
		frontUserService.update(a);
		model.addAttribute("nick", user.getName());
		model.addAttribute("email", user.getEmail());
		model.addAttribute("mobile", user.getMobile());
		return "redirect:personal";
	}

	// 修改密码
	@RequestMapping(value = "/modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, String repeatPassword, HttpServletRequest request,
			RedirectAttributes redirectAttributes, HttpServletResponse response, Model model) {
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)
				&& StringUtils.isNotBlank(repeatPassword)) {
			if (!newPassword.equals(repeatPassword)) {
				redirectAttributes.addFlashAttribute("message", "两次密码输入不一致");
				return "redirect:personal";
			}
			// else if(!newPassword.matches(regex)){
			// redirectAttributes.addFlashAttribute("message",
			// "修改密码失败，密码格式为6-16位数字和字母的组合");
			// return "redirect:personal";
			// }
			else {
				User user = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
				if (user == null) {
					redirectAttributes.addFlashAttribute("message", "未查询到用户信息");
					return "redirect:index";
				}
				user = userService.get(user.getId());// 目的:获取密码,redis没有密码
				if (SystemService.validatePassword(oldPassword, user.getPassword())) {
					systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
					user.setPassword(null);
					// jedisClient.expire(MobileJsonController.FRONT_USER+" :
					// "+token, 30* 24 * 60 * 60);
					redirectAttributes.addFlashAttribute("message", "修改密码成功");
					return "redirect:index";
				} else {
					redirectAttributes.addFlashAttribute("message", "修改密码失败，旧密码错误");
					return "redirect:personal";
				}
			}
		} else {
			redirectAttributes.addFlashAttribute("message", "信息填写不完整");
			return "redirect:personal";
		}
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String doLogin(HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response, Model model) throws Exception {
		String password = (String) request.getParameter("glandp");
		String username = (String) request.getParameter("glandu");
		// 返回页面，先从地址参数中获取返回路径，如果没有则从session中获取
		User user = new User();
		user.setLoginName(username);
		List<User> userList = userService.findList(user);
		if (userList != null && !userList.isEmpty()) { // 存在用户
			user = userList.get(0);
			user.setOffice(officeService.get(user.getOffice()));
			if (user.getLoginFlag().equals("1") && "1".equals(user.getOffice().getUseable())) {
				// 比对密码
				if (SystemService.validatePassword(password, user.getPassword())) {
					user = userList.get(0);
					Office office = officeService.get(user.getOffice()); // 用户所属部门
					user.setOffice(office);
					HttpSession session = request.getSession();
					session.setAttribute(GOV_USER_IN_SESSION, user);
					session.setMaxInactiveInterval(-1);//session不过期
					
					Cookie cookie = new Cookie("autoLogin", user.getLoginName()+"#"+user.getPassword());
					cookie.setPath(request.getContextPath());
					cookie.setMaxAge(30* 24 * 60 * 60);
					response.addCookie(cookie);
					return "redirect:customRent";
				}
				redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
				return "redirect:index";
			} else {
				redirectAttributes.addFlashAttribute("message", "该账号已禁用");
				return "redirect:index";
			}
		} else {
			redirectAttributes.addFlashAttribute("message", "用户名不存在");
			return "redirect:index";
		}
	}

	/**
	 * 退出系统
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute(GOV_USER_IN_SESSION);
		if (user != null) {
			request.getSession().invalidate();
			Cookie cookie = new Cookie("autoLogin","");
			cookie.setPath(request.getContextPath());
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		return "redirect:index";
	}

}
